<?php

namespace app\site\service\site;

use app\common\exception\MiException;
use app\common\job\Queue;
use app\common\service\CommonOrderService;
use app\common\service\pay\WxpayService;
use app\common\service\CommonSiteConfigService;
use app\model\store\Order;
use app\model\store\OrderItem;
use app\model\store\OrderRefund;
use app\site\service\delivery\DeliveryExpressService;
use app\site\service\delivery\DeliveryOrderItemService;
use app\site\service\delivery\DeliveryOrderService;
use app\site\service\traits\InstanceTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\facade\Db;

class OrderService extends \app\site\service\SiteBaseService
{

    use InstanceTrait;

    function initialize()
    {
        $this->model = new Order();
    }

    /**
     * @inheritDoc
     */
    function formatData(array $data): array
    {
        return $data;
    }

    function query(): Query
    {
        return $this->setWith(['user','items','deliveryOrders','deliveryItems','refunds'])->makeQuery()->filter(function ($v) {
            $v->userAddress = miUnserialize($v->user_address);
            // 未处理的售后
            $v->waitOrderRefund = OrderRefund::with('items')->where('order_id', $v->id)->where('audit_status', 0)->find();
            $v->payTime = miDate('Y-m-d H:i:s', $v->pay_time);
            $v->deliveryTime = miDate('Y-m-d H:i:s', $v->delivery_time);
        });
    }


    /** 通过销售订单发货
     * @return void
     * @throws MiException
     */
    public function sendGoodsBySaleOrder(int $orderId, array $sendOrderItemsArr, int $expressId, string $expressOrderNo){

        if (count($sendOrderItemsArr)==0) throw new MiException("缺少发货商品");
        if ($expressId==0) throw new MiException("缺少快递公司");
        if (!$expressOrderNo) throw new MiException("缺少快递单号");

        // 订单是否全部发货
        $order = null;

        Db::transaction(function() use ($orderId, $sendOrderItemsArr, $expressId, $expressOrderNo, &$order) {

            $order = Order::lock(true)->find($orderId);    // 需要发货的订单信息
            if (!$order){
                throw new MiException("没有查询到订单信息");
            }

            // 查询订单是否全部发货
            if ($order->delivery_status == 1){    // 订单已全部发货
                throw new MiException("订单已全部发货");
            }
            // 选择的快递公司
            $express = DeliveryExpressService::instance()->setPkWhere($expressId)->find();
            if (!$express){
                throw new MiException("没有查询到快递公司信息");
            }
            // 创建发货单
            $dOrder = DeliveryOrderService::instance()->create([
                'order_id' => $order->id,
                'express_id' => $express->id,
                'express_title' => $express->title,
                'express_kd100' => $express->kd100_code,
                'express_order_no' => $expressOrderNo,
            ]);
            foreach ($sendOrderItemsArr as $it){
                // 创建发货单商品
                DeliveryOrderItemService::instance()->create([
                    'order_id' => $order->id,
                    'delivery_order_id' => $dOrder['id'],
                    'order_item_id' => $it['id'],
                    'goods_id' => $it['goods_id'],
                    'goods_image' => $it['goods_image'],
                    'goods_title' => $it['goods_title'],
                    'goods_sku_id' => $it['goods_sku_id'],
                    'goods_sku' => $it['goods_sku'],
                    'num' => $it['num'],
                ]);
                // 修改订单商品的发货状态(暂时只有全部发货功能)
                // todo: 部分发货待开发
                OrderItem::update([
                    'delivery_status' => 1, // 全部发货
                    'delivery_time' => time()
                ], ['id'=>$it['id']]);

            }
            // 查询当前订单是否还有【未全部发货】的商品
            $unDelivery = OrderItem::where('order_id',$order->id)->whereRaw(" delivery_status=0 OR delivery_status=2 ")->find();
            if ($unDelivery){    // 订单部分发货
                $order->delivery_status = 2;    // 部分发货
            }else{  // 订单全部发货
                // 修改订单状态为已发货
                $order->order_status = 'receive';   // 待收货
                $order->delivery_status = 1;    // 全部发货

                // 发送自动确认收货的队列消息
                $config = CommonSiteConfigService::instance()->getConfigValue($this->siteId, CommonSiteConfigService::STORE);
                $delay = $config['order_receive_delay'];
                Queue::instance()->send('orderReceive', ['order_id'=>$order->id], $delay);

            }

            if ($order->delivery_time == 0){    // 首次发货，保存发货时间
                $order->delivery_time = time();
            }
            // 更新订单信息
            $order->save();

        });

        return $order;

    }


    /**
     * 确认收货
     * @param Order $order
     * @return void
     */
    public function receive(Order $order){
        CommonOrderService::instance()->receive($order->id);
    }

    /**
     * 关闭订单
     * @param Order $order
     * @param string $closeType
     * @return void
     * @throws MiException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function close(Order $order, string $closeType){
        CommonOrderService::instance()->close($order->id, $closeType);
    }

}
